package urban;

import java.util.ArrayList;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * @author emily
 * 
 */
public class Search {

	ArrayList<Letter> all;
	SortedSet<Sentence> topSentences = new TreeSet<Sentence>();
	String[] letterArray;

	public Search(ArrayList<Letter> all, String[] letterArray) {
		this.all = all;
		this.letterArray = letterArray;
		System.err.println("Starting search");
		this.populateMap();
	}

	public SortedSet<Sentence> getTopSentences() {
		return this.topSentences;
	}

	public void populateMap() {

		for (Letter l : all) {
			ArrayList<Word> w = l.getArrayList();

			if(w.isEmpty()) System.out.println("Did not produce any words for letter "+l.letter);
			for (Word s : w) {
				ArrayList<Sentence> sent = s.getArrayList();
				for (Sentence se : sent) {
					int count = 0;
					String sentence = se.getSentence();
					String[] split = sentence.split(" ");
					String firstLetter = "";
					for (int i = 0; i < split.length; i++) {
						// If the word is not more than one letter then don't worry about it.
						split[i] = trimSymbols(split[i].trim());
						if(split[i].length() > 1)
							firstLetter = split[i].substring(0, 1);
						else
							continue;
						int letInd = -1;
						if (firstLetter == null) {
							letInd = 1;
						}
						// Exit loop if the first letter isn't a letter.
						if (letInd > 0)
							continue;
						// Find the letter that corresponds with the word.
						int k = 0;
						int ind = -1;
						for(String let : letterArray) {
							if(let.equalsIgnoreCase(firstLetter)) {
								ind = k;
								break;
							}
							k++;
						}
						if (ind < 0 || ind > 2)
							continue;
						ArrayList<Word> wordSearch = all.get(ind)
								.getArrayList();
						for (Word wS : wordSearch) {
							if (wS.getWord().equalsIgnoreCase(split[i])) {
								count++;
							}
						}
					}
					se.setNumUrbanWord(count);
					topSentences.add(se);
				}
			}
		}
	}
	
	public String trimSymbols(String w) {
		String[] symbols = { "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "~", "`", ",", ".", "/", "?", ":", ";", "\"", "'", "[", "]", "=", "+", "-", "\\" };
		for(String t : symbols) {
			w.replace(t, "");
		}
		return w;
	}

}
